package bupt.party.online.dao.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateTemplate;

import bupt.party.online.dao.IAdminDao;
import bupt.party.online.model.Admin;
import bupt.party.online.model.Branch;

public class AdminDaoImpl implements IAdminDao {
	private HibernateTemplate hibernateTemplate;

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public List<Admin> select(Admin beanObject) {
		// TODO Auto-generated method stub
		return null;
	}

	public boolean delete(Admin beanObject) {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean insert(Admin beanObject) {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean saveOrUpdate(Admin beanObject) {
		try{
			this.hibernateTemplate.saveOrUpdate(beanObject);
			return true;
		}catch(Exception e ){
			e.printStackTrace();
			return false;
		}
		
		
	}

	public List<Admin> queryByCriteria(DetachedCriteria criteria) {
		// TODO Auto-generated method stub
		return null;
	}

	public void delete(Long id) {
		// TODO Auto-generated method stub
		
	}

	public void save(Admin user) {
		// TODO Auto-generated method stub
		
	}

	public void update(Admin user) {
		// TODO Auto-generated method stub
		
	}

	public List<Admin> findAll() {
		// TODO Auto-generated method stub
		return null;
	}

	public List<Admin> findBySqlString(String sql) {
		// TODO Auto-generated method stub
		return null;
	}

	public List<Admin> find(String queryString, Object... values) {
		// TODO Auto-generated method stub
		return null;
	}

	public Integer getRecordAcount(DetachedCriteria criteria) {
		// TODO Auto-generated method stub
		return null;
	}

	public List<Admin> findPageResult(DetachedCriteria criteria,
			int firstResult, int maxResult) {
		// TODO Auto-generated method stub
		return null;
	}

	public Admin findAdminByUserIdAndPassword(String userId, String password) {
		String sql = "from Admin where  isDelete=0  and adminNo="+userId+" and  adminPassword= "+password;
		List<Admin> adminList = (List<Admin>)this.hibernateTemplate.find(sql);
		if(adminList.size()>0){
			return adminList.get(0);
		}else{
			return null;
		}
		
	}

	@Override
	public boolean saveOrUpdateAdmin(Admin adminObject) {
		try{
			this.hibernateTemplate.saveOrUpdate(adminObject);
			return true;
		}catch(Exception e ){
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public String findAdminNameByAdminNO(String adminNO) {
		String sql = " select adminName from Admin where adminNo="+adminNO;
		Session session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
		
		try{
			Query q = session.createQuery(sql);
			
			String  adminName = (String) q.uniqueResult();
			
			return adminName;
			
		}catch(Exception e){
			e.printStackTrace();
			return "";
		}
	}

	@Override
	public Admin findAdminByAdminNO(String adminNO) {
		String sql = "from Admin where isDelete=0  and adminNo='"+adminNO+"'";
		List<Admin> list = this.hibernateTemplate.find(sql);
		
		if(list.size()>0){
			return list.get(0);
		}else{
			
		return null;
		}
	}

	@Override
	public Admin findAdminByAdminNOAndBranchIds(String adminNO,
			Set<Integer> branch_ids) {
		
		String branch_ids_toString = "";//先拼一下成为字符串
		String sub_branch_ids = "";
		
		if(branch_ids.size()>0){
			
			for(Iterator<Integer> itor= branch_ids.iterator(); itor.hasNext();) {
				   Integer i = (Integer)itor.next();
				   branch_ids_toString+= i +",";
				}
			//去掉最后的“，”
			sub_branch_ids = branch_ids_toString.substring(0,branch_ids_toString.length()-1);
		}
		
		if("".equals(sub_branch_ids))  sub_branch_ids = "-1";
		
		
		Session session = this.hibernateTemplate.getSessionFactory().openSession();
		try{
			
			String sql = "from Admin where is_delete=0  and  admin_no='"+adminNO+"'  " +
					"and  admin_manageBranchId  in ("+sub_branch_ids+")";
			
			Query query = session.createQuery(sql);
			
			
			return query.list().size()==0?null:(Admin) query.list().get(0);
			
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
		
		
	}

	@Override
	public DetachedCriteria getDetachedCriteria(Integer highLevelQuery,
			String queryContent, Integer firstpa, Integer secondpa,String adminNO) {
		
		DetachedCriteria criteria = DetachedCriteria.forClass(Admin.class);
		criteria.addOrder(Order.asc("adminName"));//按照管理员姓名 拼音升序排序
		
		
		//根据工号判断这个管理员的level
		int level = -1;
		int branchId = 0;
		Admin admin = new Admin();
		String sqlString = "from Admin where isDelete = 0  and adminNo='"+adminNO+"'";
		List<Admin> adminList =  this.hibernateTemplate.find(sqlString);
		
		if(adminList!=null&&adminList.size()>0){
			admin = adminList.get(0);
			level = admin.getAdminLevel(); // 可能是3  校党委；也可能是2  分党委
			branchId = admin.getAdminManageBranchId();//管理员的支部id
		} 
		
		
		if(highLevelQuery == -1 && firstpa == -1  && secondpa == -1){
			
			if(level == 2){//分党委
				String sql = "from Branch where isDelete=0 and  parentId="+branchId;
				List<Branch> list = this.hibernateTemplate.find(sql);
				
				List<Integer> idList = new ArrayList<Integer>();
				
				for(int i=0;i<list.size();i++){
					idList.add(list.get(i).getId());
				}
				Integer[] idArray = new Integer[list.size()];
				int i = 0;
				for (Integer integer : idList) {
					idArray[i++] = integer;
				}
				
				criteria.add(Restrictions.in("adminManageBranchId", idArray));
				
			}else if(level == 3){//校党委
				
				String sql = "from Branch where isDelete=0 and  (level=2 or level=3)"; //所有的分党委管理员 和 党支部管理员
				List<Branch> list = this.hibernateTemplate.find(sql);
				
				List<Integer> idList = new ArrayList<Integer>();
				
				for(int i=0;i<list.size();i++){
					idList.add(list.get(i).getId());
				}
				Integer[] idArray = new Integer[list.size()];
				int i = 0;
				for (Integer integer : idList) {
					idArray[i++] = integer;
				}
				
				criteria.add(Restrictions.in("adminManageBranchId", idArray));
				
			}
			
			
			
			return criteria;
		}else{//管理员输入了查询条件
			
			// 首先判断高级搜索是否选了姓名、工号或者身份证中的一个，就进行如下的设置
			if(highLevelQuery != -1 && queryContent != ""  && queryContent.trim().length() > 0){
				if(highLevelQuery == 1){//按姓名
					criteria.add(Restrictions.like("adminName", "%"+queryContent.trim()+"%"));
				}else if (highLevelQuery == 2) { // 按照工号
					criteria.add(Restrictions.like("adminNo", "%"
							+ queryContent.trim() + "%"));

				} else if (highLevelQuery == 3) { // 按照身份证
					criteria.add(Restrictions.like("adminIdentity", "%"
							+ queryContent.trim() + "%"));
				}
			}
			
			
			
			//继续添加限制条件
			if(secondpa != -1){//选择了支部
				criteria.add(Restrictions.eq("adminManageBranchId", secondpa));
			}else{
				if (firstpa != -1  && level == 2  ){//查询的是分党委的所有支部管理员
					String sql = "from Branch where isDelete=0 and parentId="+firstpa;
					List<Branch> list = this.hibernateTemplate.find(sql);
					
					List<Integer> idList = new ArrayList<Integer>();
					
					for(int i=0;i<list.size();i++){
						idList.add(list.get(i).getId());
					}
					Integer[] idArray = new Integer[list.size()];
					int i = 0;
					for (Integer integer : idList) {
						idArray[i++] = integer;
					}
					
					criteria.add(Restrictions.in("adminManageBranchId", idArray));
				}else if (firstpa != -1  && level == 3  ){//查询的是这个分党委、以及分党委下属的党支部 管理员
					String sql = "from Branch where isDelete=0 and (parentId="+firstpa+"  or id="+firstpa+")";
					List<Branch> list = this.hibernateTemplate.find(sql);
					
					List<Integer> idList = new ArrayList<Integer>();
					
					for(int i=0;i<list.size();i++){
						idList.add(list.get(i).getId());
					}
					Integer[] idArray = new Integer[list.size()];
					int i = 0;
					for (Integer integer : idList) {
						idArray[i++] = integer;
					}
					
					criteria.add(Restrictions.in("adminManageBranchId", idArray));
				}else if(firstpa == -1 && level == 2 ){//当firstPa=-1  并且是一个分党委 管理员 的时候 
					
					String sql = "from Branch where isDelete=0 and  parentId="+branchId;
					List<Branch> list = this.hibernateTemplate.find(sql);
					
					List<Integer> idList = new ArrayList<Integer>();
					
					for(int i=0;i<list.size();i++){
						idList.add(list.get(i).getId());
					}
					Integer[] idArray = new Integer[list.size()];
					int i = 0;
					for (Integer integer : idList) {
						idArray[i++] = integer;
					}
					
					criteria.add(Restrictions.in("adminManageBranchId", idArray));
					
				}else if(firstpa == -1 && level == 3 ){//当firstPa=-1  并且是校党委 管理员 的时候 
					
					String sql = "from Branch where isDelete=0 and  (level=2 or level=3)"; //所有的分党委管理员 和 党支部管理员
					List<Branch> list = this.hibernateTemplate.find(sql);
					
					List<Integer> idList = new ArrayList<Integer>();
					
					for(int i=0;i<list.size();i++){
						idList.add(list.get(i).getId());
					}
					Integer[] idArray = new Integer[list.size()];
					int i = 0;
					for (Integer integer : idList) {
						idArray[i++] = integer;
					}
					
					criteria.add(Restrictions.in("adminManageBranchId", idArray));
					
				}
			}
			
		}
		
		return criteria;
	}

	@Override
	public int queryAdminCountWithCriteria(DetachedCriteria detachedCriteria) {
		
		Session session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
		try{
			Criteria criteria = detachedCriteria
					.getExecutableCriteria(session);
			return Integer.parseInt(criteria.setProjection(Projections.rowCount())
					.uniqueResult().toString());
		}catch(Exception e) {
			e.printStackTrace();
			return 0;
		} 
	}

	@Override
	public List<Admin> queryAdminWithCriteria(
			DetachedCriteria detachedCriteria, int firstResult, int maxResults) {
		
		List<Admin>  list;
		if(maxResults==0){
			list = this.hibernateTemplate.findByCriteria(detachedCriteria);
		}else{
			list = this.hibernateTemplate.findByCriteria(detachedCriteria, firstResult, maxResults);
		}
		
		return list;
	}

	@Override
	public boolean deleteAdminByAdminNO(String adminNO) {
		
		Admin admin = this.findAdminByAdminNO(adminNO);
		
		if(admin!=null && admin.getIsDelete()==0){
			admin.setIsDelete(1);
			boolean b1 = this.saveOrUpdateAdmin(admin);
			if(b1==true) 
				return true;
			else 
				return false;
		}else
			return false;
	}
}
